package com.sinosoft.brokerchannel.server;

import com.sinosoft.brokerchannel.base.bins.SystemConfigRule;
import com.sinosoft.brokerchannel.base.common.SystemParamFinal;
import com.sinosoft.brokerchannel.base.dao.SystemConfigRuleMapper;
import com.sinosoft.brokerchannel.base.utile.BusinessException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @类描述:系统配置参数服务
 */
@Service
public class SystemConfigService {
    private static final Logger logger = LoggerFactory.getLogger(SystemConfigService.class);
    private static final Map<String, String> map = new HashMap<>();
    @Autowired
    private SystemConfigRuleMapper systemConfigRuleMapper;

    /**
     * 清空缓存信息
     */
    public static synchronized void clear() {
        map.clear();
        logger.info("Clear SysConfig cahce success!");
    }

    /**
     * @param key
     * @return 系统配置信息
     * @throws Exception
     * @描述:获取系统配置参数，存在systemConfigRule中
     */
    public String getProperty(String key) throws BusinessException {
        String rule = "";
        try {
            if (map.containsKey(key)) {
                rule = map.get(key);
            } else {
                SystemConfigRule systemConfigRule = new SystemConfigRule();
                String systemCode = "channel";
                systemConfigRule.setSystemcode(systemCode);
                systemConfigRule.setParamcode(key);
                systemConfigRule.setSerialno(1);
                systemConfigRule = systemConfigRuleMapper.selectByPrimaryKey(systemConfigRule);
                if (systemConfigRule == null) {
                    throw new BusinessException("0002", "获取系统配置参数失败！");
                }
                map.put(systemConfigRule.getParamcode(), systemConfigRule.getRule());
                rule = systemConfigRule.getRule();
            }
        } catch (Exception e) {
            logger.info(SystemParamFinal.Exception_LOG, e);
            throw new BusinessException("0002", "获取系统配置参数失败！");
        }
        return rule;
    }

    /**
     * 清除缓存信息
     */
    public String removeCache(String key) throws BusinessException {
        String rule = "";
        String rule2 = "";
        if (map.containsKey(key)) {
            rule = map.get(key);
            map.remove(key);
            rule2 = this.getProperty(key);
            return "开始的缓存" + rule + "数据库修改的值" + rule2;
        } else {
            return "map缓存为空！！";
        }
    }

}
